package com.app.newcsc.viewmodel;

import android.app.Application;
import android.util.Log;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;

import com.app.newcsc.BR;
import com.app.newcsc.R;
import com.app.newcsc.app.AppApplication;
import com.app.newcsc.data.DemoRepository;
import com.app.newcsc.entity.PayAccountEntity;
import com.app.newcsc.entity.TransactionPlanEntity;
import com.app.newcsc.entity.TransactionPlanListData;
import com.app.newcsc.entity.UserEntity;
import com.app.newcsc.http.response.ApiException;
import com.app.newcsc.utils.TextUtil;
import com.app.newcsc.utils.ToastUtil;
import com.app.newcsc.utils.Utils;

import java.util.HashMap;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;
import okhttp3.ResponseBody;

/**
 * @author: woking
 * @date: 2021/6/7
 * @description：
 */
public class TransactionTabViewModel extends BaseViewModel<DemoRepository> {
    public SingleLiveEvent<TransactionTabItemViewModel> deleteItemLiveData = new SingleLiveEvent<>();

    public SingleLiveEvent<TransactionTabItemViewModel> buySellItemLiveData = new SingleLiveEvent<>();//监听买卖按钮

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    //使用LiveData
    public SingleLiveEvent<Boolean> isBuy = new SingleLiveEvent<>();//true买 FALSE卖
    public SingleLiveEvent<String> type = new SingleLiveEvent<>();//0全部 1： 1-10 2 11-99 3 100-500

    public SingleLiveEvent<Boolean> isreflsh = new SingleLiveEvent<>();
    public SingleLiveEvent<List<PayAccountEntity>> mPayAccountEntitys = new SingleLiveEvent<>();//获取支付方式
    private int page = 1;

    public class UIChangeObservable {
        //下拉刷新完成
        public SingleLiveEvent finishRefreshing = new SingleLiveEvent<>();
        //上拉加载完成
        public SingleLiveEvent finishLoadmore = new SingleLiveEvent<>();
    }

    public TransactionTabViewModel(@NonNull Application application, DemoRepository repository) {
        super(application, repository);
    }

    //给RecyclerView添加ObservableList
    public ObservableList<TransactionTabItemViewModel> observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding
    public ItemBinding<TransactionTabItemViewModel> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_transaction_tab_item);

    //下拉刷新
    public BindingCommand onRefreshCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            requestNetWork(false);
        }
    });

    public void onRefresh()
    {
        requestNetWork(false);
    }

    public void onLoadMore()
    {
        requestNetWork(true);
    }

    //上拉加载
    public BindingCommand onLoadMoreCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            onLoadMore();
        }
    });


    public void requestNetWork(boolean isLoadMore) {
        Log.e("TAG",type.getValue()+"====type======requestNetWork========isBuy====="+isBuy.getValue());
        if(!isLoadMore)
        {
            page = 1;
        }
//        else {
//            page++;
//        }
        String typeStr = isBuy.getValue() ? "1" : "2";//filter[type]=1    我要买； filter[type]=2    我要卖
        String num_zone = type.getValue();
        String sort = isBuy.getValue() ? "price" : "-price";;
        model.planLists(typeStr,sort,num_zone,page+"")
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
//                        showDialog("正在请求...");
//                        showDialog(null);
                    }
                })
                .subscribe(new DisposableObserver<BaseResponse<List<TransactionPlanEntity >>>() {
                    @Override
                    public void onNext(BaseResponse<List<TransactionPlanEntity>> response) {
//                        dismissDialog();
//                        Log.e("TAG","===========planList========onNext====="+response.getCode());
                        if(!isLoadMore)
                        {
                            //清除列表
                            observableList.clear();
                        }
                        if(null != response && null != response.getData() && response.getData().size() > 0)
                        {
                            for (TransactionPlanEntity entity : response.getData())
                            {
                                TransactionTabItemViewModel itemViewModel = new TransactionTabItemViewModel(TransactionTabViewModel.this, entity);
                                //双向绑定动态添加Item
                                observableList.add(itemViewModel);
                            }

                            if(response != null && null != response.meta && null != response.meta.pagination)
                            {
                                page = response.meta.pagination.current_page;
                                page++;
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("TAG","===========planList========onError====="+throwable.getMessage());
                        //关闭对话框
//                        dismissDialog();
                        if(!isLoadMore)
                        {
                            //请求刷新完成收回
                            uc.finishRefreshing.call();
                        }
                        else
                        {
                            uc.finishLoadmore.call();
                        }

                        if (throwable instanceof ResponseThrowable) {
                            String msg = ApiException.getShowmessage(((ResponseThrowable) throwable).errorBody);
                            ToastUtils.showShortSafe(msg);

                            int code = ((ResponseThrowable) throwable).code;
                            if((!TextUtil.isEmpty(msg) && msg.contains("被禁")) || code == 403)
                            {
                                if(TextUtil.isEmpty(AppApplication.userJinYongMsg))
                                {
                                    AppApplication.userJinYongMsg = msg;
                                }
                                if(observableList.size() > 0)
                                {
                                    //清除列表
                                    observableList.clear();
                                    page = 1;
                                }
                            }
                            else
                            {
                                if(!TextUtil.isEmpty(AppApplication.userJinYongMsg))
                                {
                                    AppApplication.userJinYongMsg = "";
                                }
                            }
                        }
                    }

                    @Override
                    public void onComplete() {
                        Log.e("TAG","===========planList========onComplete=====");
                        //关闭对话框
//                        dismissDialog();
                        if(!isLoadMore)
                        {
                            //请求刷新完成收回
                            uc.finishRefreshing.call();
                        }
                        else
                        {
                            uc.finishLoadmore.call();
                        }
                        if(!TextUtil.isEmpty(AppApplication.userJinYongMsg))
                        {
                            AppApplication.userJinYongMsg = "";
                        }
                    }
                });
    }

    public void otcBuy(String id,String type,String num,String payment_password,String idcard,String code) {
        Log.e("TAG","====type======requestNetWork========isBuy====="+isBuy.getValue());

        model.otcBuy(id, type, num, payment_password, type.equals("1") ? null : idcard, type.equals("1") ? null : code)
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
//                        showDialog(null);
                    }
                })
                .subscribe(new DisposableObserver<ResponseBody>() {
                    @Override
                    public void onNext(ResponseBody response) {
//                        dismissDialog();
                        Log.e("TAG","===========otcBuy========onNext=====");
//                        if(null != response && null != response.getData())
//                        {
//                            for (TransactionPlanEntity entity : response.getData())
//                            {
//                                TransactionTabItemViewModel itemViewModel = new TransactionTabItemViewModel(TransactionTabViewModel.this, entity);
//                                //双向绑定动态添加Item
//                                observableList.add(itemViewModel);
//                            }
//                        }

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("TAG","===========otcBuy========onError====="+throwable.getMessage());
                        //关闭对话框
                        dismissDialog();
                        if (throwable instanceof ResponseThrowable) {
                            ToastUtils.showShortSafe(ApiException.getShowmessage(((ResponseThrowable) throwable).errorBody));
//                            ToastUtils.showShort("提交失败");
                        }
                    }

                    @Override
                    public void onComplete() {
                        Log.e("TAG","===========otcBuy========onComplete=====");
                        //关闭对话框
                        dismissDialog();
                        ToastUtils.showShortSafe("提交成功");
                        isreflsh.postValue(isBuy.getValue());
                    }
                });
    }
    /**
     * 短信验证码
     */
    public void smsCode(TextView send_yzm_tv)
    {
        UserEntity mUserEntity = ((AppApplication)AppApplication.getInstance()).getUserEntity();
        if(mUserEntity == null)
        {
            ToastUtil.showToast("手机号为空");
            return;
        }
        //type:手机验证码类型：1:注册，2:找回密码，3:更换手机号, 4:添加银行卡, 5:设置支付密码,6: 登陆, 11: otc支付, 12: 挂单 用户, 13:挂单 订单
        HashMap<String, Object> map = new HashMap<>();
        map.put("type","13");//类型:1=购买,2=出售
        map.put("phone",((AppApplication)AppApplication.getInstance()).getUserEntity().mobile);//挂单数量

        model.smsCode(map)
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
//                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<ResponseBody>() {
                    @Override
                    public void onNext(ResponseBody response) {
                        Log.e("TAG","============smsCode=====onNext========");
                        if(null != response)
                        {
//                            mPlanIndexEntity.setValue(response.getData());
                        }
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("TAG","============smsCode=====onError========");
                        if (throwable instanceof ResponseThrowable) {
                            ToastUtils.showShortSafe(((ResponseThrowable) throwable).message);
                        }
                    }
                    @Override
                    public void onComplete() {
                        Log.e("TAG","============smsCode=====onComplete========");
                        ToastUtils.showShortSafe("发送成功");
                        send_yzm_tv.setEnabled(false);
//                        send_yzm_tv.setBackgroundResource(R.drawable.shape_d9dade_50);
                        Utils.showCount(send_yzm_tv);
                    }
                });
    }
    public void requestNetWork2(boolean isLoadMore) {
        Log.e("TAG",type.getValue()+"====type======requestNetWork========isBuy====="+isBuy.getValue());
        //可以调用addSubscribe()添加Disposable，请求与View周期同步
//        http://csc.chaishows.com/api/otc/plan/list?type=1&lang=zh-cn HTTP/1.1 page=1&keyword=&num_zone=1-10
        if(!isLoadMore)
        {
            page = 1;
        }
        else {
            page++;
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("type",isBuy.getValue() ? "1" : "2");
        map.put("lang","zh-cn");
        map.put("page",page+"");
        map.put("keyword","");
        map.put("num_zone",type.getValue());
        model.planList(map)
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
//                        showDialog("正在请求...");
//                        showDialog(null);
                    }
                })
                .subscribe(new DisposableObserver<BaseResponse<TransactionPlanListData>>() {
                    @Override
                    public void onNext(BaseResponse<TransactionPlanListData> response) {
//                        dismissDialog();
//                        Log.e("TAG","===========planList========onNext====="+response.getCode());
                        if(!isLoadMore)
                        {
                            //清除列表
                            observableList.clear();
                        }
                        //请求成功
                        if (response.getCode() == 200) {
//                            for (DemoEntity.ItemsEntity entity : response.getResult().getItems()) {
                            if(response.getData().list.data != null && response.getData().list.data.size() > 0)
                            {
//                                page = response.getData().list.current_page;
//                                for (TransactionPlanListData.PlanList.PlanData entity : response.getData().list.data) {
//                                    TransactionTabItemViewModel itemViewModel = new TransactionTabItemViewModel(TransactionTabViewModel.this, entity);
//                                    //双向绑定动态添加Item
//                                    observableList.add(itemViewModel);
//                                }
                            }
                            else
                            {
                                ToastUtils.showShortSafe("没有更多数据了");
                            }
                        } else {
                            //code错误时也可以定义Observable回调到View层去处理
//                            ToastUtils.showShortSafe("数据错误");
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("TAG","===========planList========onError====="+throwable.getMessage());
                        //关闭对话框
//                        dismissDialog();
                        //请求刷新完成收回
                        uc.finishRefreshing.call();
                        if (throwable instanceof ResponseThrowable) {
                            ToastUtils.showShortSafe(((ResponseThrowable) throwable).message);
                        }
                    }

                    @Override
                    public void onComplete() {
                        Log.e("TAG","===========planList========onComplete=====");
                        //关闭对话框
//                        dismissDialog();
                        if(!isLoadMore)
                        {
                            //请求刷新完成收回
                            uc.finishRefreshing.call();
                        }
                        else
                        {
                            uc.finishLoadmore.call();
                        }
                    }
                });
    }
    /**
     * 删除条目
     *
     * @param netWorkItemViewModel
     */
    public void deleteItem(TransactionTabItemViewModel netWorkItemViewModel) {
        //点击确定，在 observableList 绑定中删除，界面立即刷新
        observableList.remove(netWorkItemViewModel);
    }

    /**
     * 获取条目下标
     *
     * @param netWorkItemViewModel
     * @return
     */
    public int getItemPosition(TransactionTabItemViewModel netWorkItemViewModel) {
        return observableList.indexOf(netWorkItemViewModel);
    }
    public void otcPayCccount() {
        Log.e("TAG","==========otcPayCccount=============");

        model.otcPayCccount()
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResponse<List<PayAccountEntity>>>() {
                    @Override
                    public void onNext(BaseResponse<List<PayAccountEntity>> response) {
                        Log.e("TAG","==========otcPayCccount=======onNext======");
//                        dismissDialog();
                        //请求成功
                        if (response != null && null != response.getData() && response.getData().size() > 0) {
                            mPayAccountEntitys.postValue(response.getData());
                        }
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("TAG","==========otcPayCccount=========onError====");
                        //关闭对话框
                        dismissDialog();
                    }

                    @Override
                    public void onComplete() {
                        Log.e("TAG","==========otcPayCccount=====onComplete========");
                        //关闭对话框
                        dismissDialog();
                    }
                });
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}